package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.CirclemapDTO;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParm;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Override
    public List<GeofenceVO> selectgeofence(GeofenceQuery geofenceQuery) {
        List<GeofenceVO> list = geofenceMapper.selectgeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParm geofenceParm) {
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParm,geofence);
        //前端数据是key:value结构
        //{type: 'rectangle', recPoints: '116.39353016292587-39.90577752308682,116.404237964…367425468599,116.39353016292587-39.90367425468599'}
        //JSON处理库工具
        HashMap<String,String> position = geofenceParm.getPosition();
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            //这个方法如果传入null值或者字段不匹配会抛出异常,所以置于try-catch中来处理
            String positionStr = objectMapper.writeValueAsString(position);
            if (geofenceParm.getId()!=null){//更新围栏
                geofenceMapper.update(geofence);
            }else{//新增围栏
                geofence.setStatus("1");
                geofence.setPosition(positionStr);
                geofence.setCreateTime(new Date());
                geofenceMapper.insert(geofence);
            }
        }catch (JsonProcessingException e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public void deleteGeofence(Long id) {
        geofenceMapper.deleteGeofence(id);
    }
}
